package com.angenela.lmz.advice;

import com.angenela.lmz.constant.Constant;
import com.angenela.lmz.dto.ObjectDTO;
import com.angenela.lmz.exception.UserIdException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice(basePackages = "com.angenela.lmz.controller")
public class MyExceptionHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @ExceptionHandler(UserIdException.class)
    @ResponseBody
    public String userIdException(UserIdException e) throws JsonProcessingException {
        ObjectDTO dto = new ObjectDTO();
        dto.setCode(Constant.SERVICE_ERROR_CODE);
        dto.setMessage(Constant.IMAGE_USERID_NULL);
        e.printStackTrace();
        return objectMapper.writeValueAsString(dto);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handler(Exception e) throws JsonProcessingException {
        ObjectDTO dto = new ObjectDTO();
        dto.setCode(Constant.SERVICE_ERROR_CODE);
        dto.setMessage("请检查参数是否符合规范");
        e.printStackTrace();
        return objectMapper.writeValueAsString(dto);
    }
}
